package com.bancomer.main;

import java.io.File;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

import com.bancomer.batch.Constants;
import com.bancomer.batch.MapConstants;
import com.bancomer.batch.pojo.Alert;
import com.bancomer.batch.pojo.AlertsContainer;
import com.bancomer.batch.pojo.FileHelper;
import com.bancomer.batch.pojo.PigScript;
import com.bancomer.batch.util.FilesReader;
import com.bancomer.batch.util.FilesWriter;
import com.bancomer.batch.util.LinuxCommand;
import com.bancomer.batch.util.StringConverter;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.StaxDriver;

public class MainSchedulerAuditFileWriter {
	public static void main(String[] args) throws Exception {
		String pathFileXML;
		FileHelper summary=null;
		FileHelper detail=null;
		pathFileXML =(args.length==1)?args[0]:"/home/cloudera/Documents/ALERTAS/ALERTAS.xml";
		AlertsContainer alertsContainer;
		String successFilePath="";
		XStream xstream = new XStream(new StaxDriver());
		xstream.alias("AlertsContainer", AlertsContainer.class);
		xstream.alias("Alert", Alert.class);
		xstream.alias("FileHelper", FileHelper.class);
		xstream.alias("PigScript", PigScript.class);
		alertsContainer= (AlertsContainer) xstream.fromXML(new File(pathFileXML));
		FileHelper output = alertsContainer.getAlertsOutput();
		File outputFile = null;
		int existsFileIndicator = 0;
		Logger logger = null;
		try{	
			for(Alert alert:alertsContainer.getAlerts()){
				MapConstants mapConstants = MapConstants.getInstance(alert.getProperties().getProperty("constantsFile"));
				final Properties alertConstants = mapConstants.getConstants();
				PropertyConfigurator.configure(alertConstants.getProperty("pathLog4j"));
				logger = Logger.getLogger("MainSchedulerAuditFileWriter");
				for(FileHelper file:alert.getOutputFiles()){
					if(file.getType().equals(alertConstants.getProperty("FILE_OUTPUT"))){
							if(file.getProperties().getProperty("outputType").equals(alertConstants.getProperty("OUTPUT_TYPE_SUMMARY"))){
								summary = file;
								successFilePath = file.getLocalPath();
								break;
							}
					}
				}
				File successFile = new File(successFilePath+"SUCCESS");
				if(successFile.exists()==true){
					String succesFileContent = FilesReader.readFile(successFilePath+"SUCCESS").toString();
					Constants.alertDate = succesFileContent.split("\n")[0].split("-")[1];
					output.setName(StringConverter.convertPatternToDate(output.getName()));
					outputFile = new File(output.getLocalPath(), output.getName());
					if(outputFile.exists()&&existsFileIndicator == 0){
						LinuxCommand.execute("rm -f "+output.getLocalPath()+output.getName(),true);
					}
					summary.setName(StringConverter.convertPatternToDate(summary.getName()));
					StringBuffer summaryFileBuffer = FilesReader.readFile(alertConstants.getProperty("END_OF_LINE"),summary.getLocalPath()+summary.getName());
					int indexEndOfLine = summaryFileBuffer.lastIndexOf(alertConstants.getProperty("END_OF_LINE"));
					summaryFileBuffer.deleteCharAt(indexEndOfLine);
					FilesWriter.writeFile(summaryFileBuffer.toString(), output.getLocalPath()+output.getName(), true);
				}
				existsFileIndicator++;
			}
			for(Alert alert:alertsContainer.getAlerts()){
				MapConstants mapConstants = MapConstants.getInstance(alert.getProperties().getProperty("constantsFile"));
				Properties alertConstants = mapConstants.getConstants();
				PropertyConfigurator.configure(alertConstants.getProperty("pathLog4j"));
				logger = Logger.getLogger("MainSchedulerAuditFileWriter");
				for(FileHelper file:alert.getOutputFiles()){
					if(file.getType().equals(alertConstants.getProperty("FILE_OUTPUT"))){
							if(file.getProperties().getProperty("outputType").equals(alertConstants.getProperty("OUTPUT_TYPE_DETAIL"))){
								detail=file;
								successFilePath = file.getLocalPath();
								break;
							}
					}
				}
				File successFile = new File(successFilePath+"SUCCESS");
				if(successFile.exists()==true){
					String succesFileContent = FilesReader.readFile(successFilePath+"SUCCESS").toString();
					Constants.alertDate = succesFileContent.split("\n")[0].split("-")[1];
					output.setName(StringConverter.convertPatternToDate(output.getName()));
					detail.setName(StringConverter.convertPatternToDate(detail.getName()));
					StringBuffer detailFileBuffer = FilesReader.readFile(alertConstants.getProperty("END_OF_LINE"),detail.getLocalPath()+detail.getName());
					int indexEndOfLine = detailFileBuffer.lastIndexOf(alertConstants.getProperty("END_OF_LINE"));
					detailFileBuffer.deleteCharAt(indexEndOfLine);
					FilesWriter.writeFile(detailFileBuffer.toString(), output.getLocalPath()+output.getName(), true);
				}
			}
		}
		catch(Exception e){
			logger.error("Error: "+e.getMessage());
			for(int i = 0; i<e.getStackTrace().length;i++){
				logger.error(e.getStackTrace()[i]);
			}
			output.setName(StringConverter.convertPatternToDate(output.getName()));
			FilesWriter.writeFile("", output.getLocalPath()+output.getName(), false);
			throw e;
		}
	}
}
